package com.sgb.kjwl.view.ui.fragment.packers;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtPackersEmploymentBinding;
import com.sgb.kjwl.model.entity.EmploymentEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.packers.EmploymentDetailActivity;
import com.sgb.kjwl.view.ui.adapter.packers.PackersEmploymentAdapter;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow4;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.packers.PackersEmploymentModel;
import com.sgb.link.entity.PickFilterEntity;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : younghow
 * @date : 2021/12/3 11:29
 * description:用工需求
 */
public class WorkRequirementFragment extends AppLazyFragment {

    public PackersEmploymentModel viewModel;
    private AtPackersEmploymentBinding binding;
    private PackersEmploymentAdapter adapter;

    /**
     * 工种
     */
    private List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> mWorkType;
    private PickResultEntity pickResultIndustry;
    private PickResultEntity pickResultCategory;
    private PickResultEntity pickResultWorkType;

    private PickResultEntity pickResultWorkerType;
    /**
     * 用工状态
     */
    private PickPopWindow1 mEmploymentTypePopup1;
    private PickResultEntity pickResultWorkerStatus;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private GoodsTypePopWindow4 carsTypePopWindow;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    private int typePosition = -1,mHaveWorkType;
    private String salaryType;
    private String industryNo,categoryNo,workNo;
    private String mAreaCode,mAreaName;
    private boolean isLoadMore;

    public static WorkRequirementFragment newInstance(AddressEntity context) {
        WorkRequirementFragment intent = new WorkRequirementFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("entity",context);
        intent.setArguments(bundle);
        return (intent);
    }

    public static WorkRequirementFragment newInstance(String provinceNo,String cityNo,String cityName,String industryNo,String categoryNo,String workNo,String workName,String salaryType,String areaNo,String industryName) {
        WorkRequirementFragment intent = new WorkRequirementFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("salaryType",salaryType);
        bundle.putSerializable("provinceNo",provinceNo);
        bundle.putSerializable("industryNo",industryNo);
        bundle.putSerializable("categoryNo",categoryNo);
        bundle.putSerializable("workNo",workNo);
        bundle.putSerializable("cityNo",cityNo);
        bundle.putSerializable("cityName",cityName);
        bundle.putSerializable("areaNo",areaNo);
        bundle.putSerializable("workName",workName);
        bundle.putSerializable("industryName",industryName);
        intent.setArguments(bundle);
        return (intent);
    }


    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getEmploymentList(salaryType, pickResultIndustry.getNo(), pickResultCategory.getNo(), pickResultWorkType.getNo(),
                pickResultWorkerType.getNo(), pickResultWorkerStatus.getNo(), pickResultProvince.getNo(),
                pickResultCity.getNo(), pickResultArea.getNo(), isLoadMore);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.at_packers_employment,container,false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(PackersEmploymentModel.class);

        setTextButton();

        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (position == 0) {
                    setWorkerStatusData();
                } else if (position == 1) {
                    showCityPop();
                }
            }
        });

        binding.ivEmploymentAll.setOnClickListener(this);

        carsTypeData = new ArrayList<>();
        if (adapter == null) {
            adapter = new PackersEmploymentAdapter(getContext(), null, 0);
        }

        adapter.setOnItemClick(new AdapterOnItemClick<EmploymentEntity>() {
            @Override
            public void onItemClick(EmploymentEntity employmentEntity, int position) {
                EmploymentDetailActivity.startForResult(getActivity(), employmentEntity.getNo(), employmentEntity.getProjectName(), employmentEntity.isIsApply(), 0);
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                TextUtils.isEmpty(workNo);
                initFilterData(true);
            }
        });

        pickResultIndustry = new PickResultEntity();
        pickResultCategory = new PickResultEntity();
        pickResultWorkType = new PickResultEntity();
        pickResultWorkerType = new PickResultEntity();
        pickResultWorkerStatus = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();

        AddressEntity mAddress = null;
        if (getArguments() != null) {
            mAddress = (AddressEntity) getArguments().getSerializable("entity");
        }

        if (mAddress != null) {
            pickResultIndustry.setNo((mAddress).getNo());
            pickResultIndustry.setName((mAddress).getName());
        }

        salaryType = getArguments().getString("salaryType");
        industryNo= getArguments().getString("industryNo");
        categoryNo = getArguments().getString("categoryNo");
        workNo = getArguments().getString("workNo");
        String provinceNo = getArguments().getString("provinceNo");
        String cityNo = getArguments().getString("cityNo");
        String areaNo = getArguments().getString("areaNo");
        String cityName = getArguments().getString("cityName");
        String industryName = getArguments().getString("industryName");
        if (!TextUtils.isEmpty(provinceNo)){
            pickResultProvince.setNo(provinceNo);
            pickResultCity.setNo(cityNo);
            pickResultCity.setName(cityName);
            pickResultArea.setNo(areaNo);
            binding.sct.contentSelect(cityName,true,false,1);
        }

        if (!TextUtils.isEmpty(industryNo)){
            pickResultIndustry.setNo(industryNo);
            pickResultCategory.setNo(categoryNo);
            pickResultWorkType.setNo(workNo);
            mHaveWorkType = 1;
            pickResultIndustry.setName(industryName);
        }

        binding.rvPackerChangeFirstContentTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                carsTypePopWindow.setDefItem(tab.getPosition());
                typePosition = tab.getPosition();
                if (mHaveWorkType == 1 && typePosition != 0){
                    if (!TextUtils.isEmpty(workNo)){
                        pickResultIndustry.setNo(industryNo);
                        pickResultCategory.setNo(categoryNo);
                        pickResultWorkType.setNo(workNo);
                    }

                    if (!TextUtils.isEmpty(industryNo)){
                        pickResultIndustry.setNo(industryNo);
                    }
                    initFilterData(false);
                    mHaveWorkType = -1;
                }else {
                    pickResultIndustry.setNo(mWorkType.get(tab.getPosition()).getNo());
                    pickResultCategory.setNo("");
                    pickResultWorkType.setNo("");

                    initFilterData(false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        carsTypePopWindow = new GoodsTypePopWindow4(getActivity());
        carsTypePopWindow.setBgView(binding.grayLayout);
        carsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                typePosition = (int) key2;
                pickResultIndustry.setNo(entity.getNo());
                binding.rvPackerChangeFirstContentTitle.setScrollPosition(typePosition,0,true);
                initFilterData(false);
            }
        });
        carsTypePopWindow.setOnDismissListener(() -> binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_team_employment));

        initLiveData();
    }

    private void initLiveData() {

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.employmentList.observe(getViewLifecycleOwner(), new Observer<List<EmploymentEntity>>() {
            @Override
            public void onChanged(List<EmploymentEntity> list) {
                if (isLoadMore) {
                    binding.recyclerView.loadMoreComplete();
                    if (list != null && list.size() > 0) {
                        adapter.addDatas(list);
                    }
                    binding.recyclerView.setNoMore(list.size() < 10);
                } else {
                    binding.recyclerView.refreshComplete();
                    if (list != null && list.size() > 0) {
                        binding.emptyView.setVisibility(View.GONE);
                        adapter.setDatas(list);
                        binding.recyclerView.smoothScrollToPosition(0);
                    } else {
                        adapter.clearDatas();
                        binding.emptyView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        viewModel.workType.observe(getViewLifecycleOwner(), new Observer<List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> data) {
                int index = 0;
                mWorkType = data;
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        PickFilterEntity datum = data.get(i);
                        GoodsInfoTypeEntity3 info = new GoodsInfoTypeEntity3();
                        info.setName(datum.getName());
                        info.setNo(datum.getNo());
                        carsTypeData.add(info);
                        if (!TextUtils.isEmpty(pickResultIndustry.getName()) && pickResultIndustry.getName().equals(datum.getName())) {
                            index = i;
                        }
                        binding.rvPackerChangeFirstContentTitle.addTab(binding.rvPackerChangeFirstContentTitle.newTab().setText(datum.getName()));
                    }
                }
                if (index != 0) {
                    int finalIndex = index;
                    typePosition = index;
                    binding.rvPackerChangeFirstContentTitle.postDelayed(() -> binding.rvPackerChangeFirstContentTitle.getTabAt(finalIndex).select(), 100);
                }
            }
        });

        viewModel.employmentStatus.observe(getViewLifecycleOwner(), new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> data) {
                if (mEmploymentTypePopup1 == null) {
                    int position = 0;
                    mEmploymentTypePopup1 = new PickPopWindow1(getContext());
                    mEmploymentTypePopup1.setBgView(binding.grayLayout);
                    if (!"".equals(pickResultWorkerStatus.getNo())){
                        for (int i = 0; i < data.size(); i++) {
                            if (pickResultWorkerStatus.getNo().equals(data.get(i).getNo())){
                                position = i;
                            }
                        }
                    }
                    mEmploymentTypePopup1.setOnResultClick((PickPopWindow1.OnResultClick) (key1, key2, key3) -> {
                        pickResultWorkerStatus.setNo((String) key1);
                        pickResultWorkerStatus.setName((String) key2);
                        pickResultWorkerStatus.setPosition((int) key3);
                        if (TextUtils.isEmpty((String) key2) || TextUtils.equals(getString(R.string.app_all), (String) key2)) {
                            binding.sct.contentSelect("用工状态",false,false,0);
                        } else {
                            binding.sct.contentSelect((String) key2,true,false,0);
                        }
                        initFilterData(false);
                    });

                    mEmploymentTypePopup1.setOnDismissListener(() -> binding.sct.contentSelect(!TextUtils.equals("用工状态", binding.sct.getName(0)),false,0));

                    mEmploymentTypePopup1.setData(data);
                    mEmploymentTypePopup1.setDefaultItem(position);
                }
            }
        });

        viewModel.city.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()) {
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false, 1);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setShowSimpleName(true);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    if ("".equals(pickResultProvince.getNo())){
                        pickResultProvince.setName(mAreaCode);
                    }
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!getString(R.string.app_all).equals(pickResultArea.getName()) && !"".equals(pickResultArea.getName())) {
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultCity.getName()) && !"".equals(pickResultCity.getName())) {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultProvince.getName()) && !"".equals(pickResultProvince.getName())) {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        } else {
                            binding.sct.contentSelect(getString(R.string.app_all),false,false,1);
                        }
                    });

                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!TextUtils.equals("地区", binding.sct.getName(1)),false,1));

                    if (!"".equals(pickResultCity.getNo())){
                        popCity.setDataForTeamMainPage(data, true, pickResultProvince.getNo(),pickResultCity.getNo(),pickResultArea.getNo());
                    }else {
                        popCity.setDataForAll(data, true,mAreaCode);
                    }
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        if ("".equals(pickResultProvince.getNo())){
            pickResultProvince.setNo(mAreaCode);
            binding.sct.contentSelect(mAreaName,true,false,1);
        }
        viewModel.getLinkAgeWorkType();
        viewModel.getEmploymentStatus();
        viewModel.getCityList();
        initFilterData(false);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_employment_all){
            if (carsTypeData != null && carsTypeData.size() > 0){
                carsTypePopWindow.setData(carsTypeData,typePosition);
                carsTypePopWindow.showPopwindow(binding.ivEmploymentAll, 0, 0);
            }
            binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_up_gray);
        }
    }


    public void setWorkerStatusData() {
        binding.sct.contentSelect(false,true,0);
        mEmploymentTypePopup1.showPopwindow0(binding.sct);
    }

    public void showCityPop() {
        binding.sct.contentSelect(false,true,1);
        popCity.showPopwindow(binding.sct, 0, 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            if (requestCode == 0) {
                initFilterData(false);
            }
        }
    }

    private void setTextButton(){
        SelectPopEntity selectPopEntity2 = new SelectPopEntity("用工状态", "0", false, true);
        SelectPopEntity selectPopEntity3 = new SelectPopEntity("地区", "1", false, true);
        binding.sct.addTextButton(selectPopEntity2);
        binding.sct.addTextButton(selectPopEntity3);
    }
}
